from downloader import download
import re as regex



def parse_detail(url):
    resp = download(url)
    # 解析图片
    images = resp.xpath('//div[@id="endText"]/*//img/@src').extract()

    #解析下载链接
    links = []
    tds = resp.xpath('//div[@id="main"]/*//table/*//td')
    for td in tds:
        try:
            download_type = td.xpath('text()').extract()[0]
            title = td.xpath('a/text()').extract()[0]
            link = td.xpath('a/@href').extract()[0]
            links.append({
                'type': download_type,
                'title': title,
                'link': link
            })
        except:
            continue
    #解析详情
    keys = [
        '导演', '编剧', '类型', '主演', '国家', '语言', '片长', '上映日期', 'IMDB', '剧情简介'
    ]
    info = []
    for key in keys:
        try:
            value = regex.findall(f'{key}: (.*?)<', resp.text)[0].replace('&middot;', '·')
            info.append({'key': key, 'value': value})
        except:
            continue
    intro = resp.xpath('//*[@id="endText"]/p[2]')[0].xpath('string(.)').extract()
    intro = regex.sub(r'[\r\u3000]', '', intro[0])

    if not info:
        keys = [
            '导　　演', '编　　剧', '类　　别', '主　　演', '国　　家', '语　　言', '片　　长', '年　　代'
        ]
        info = []
        for key in keys:
            try:
                value = regex.findall(f'{key}(.*?)<', resp.text)[0].replace('&middot;', '·').replace('&amp;middot;', '·')
                info.append({'key': key.replace('\u3000', ''), 'value': value.replace('\u3000', '')})
            except:
                continue
        intro = resp.xpath('//*[contains(text(),"◎简　　介　")]/following::p[1]')[0].xpath('string(.)').extract()[0].strip().replace('\u3000','').replace('&middot;', '·')
    return info, intro,links, images



